const mysql = require('mysql2/promise');

const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'demo'
};

// 测试用户数据
const users = [
    { username: 'admin', password: 'admin123' },
    { username: 'test', password: 'test123' },
    { username: 'user1', password: 'password123' }
];

async function initUsers() {
    try {
        // 创建数据库连接
        const connection = await mysql.createConnection(dbConfig);

        // 创建用户表
        await connection.execute(`
            CREATE TABLE IF NOT EXISTS users (
                id INT PRIMARY KEY AUTO_INCREMENT,
                username VARCHAR(50) UNIQUE NOT NULL,
                password VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        `);

        // 添加用户
        for (const user of users) {
            try {
                await connection.execute(
                    'INSERT INTO users (username, password) VALUES (?, ?)',
                    [user.username, user.password]  // 直接存储明文密码
                );
                console.log(`用户 ${user.username} 创建成功`);
            } catch (err) {
                if (err.code === 'ER_DUP_ENTRY') {
                    console.log(`用户 ${user.username} 已存在，跳过`);
                } else {
                    console.error(`创建用户 ${user.username} 失败:`, err);
                }
            }
        }

        console.log('所有用户初始化完成');
        await connection.end();
    } catch (error) {
        console.error('初始化用户失败:', error);
    }
}

// 运行初始化
initUsers(); 